Python 3.6 for beginners
__TOC__ I strongly recommend installing Anaconda (Python distribution). It comes with numpy and scipy preinstalled. Syntax There is one thing that every beginner needs to understand from the very start. When you tell the computer something like :Pront("I want the computer to print this to the screen") it isnt going to understand you. No matter how obvious it is to you, and indeed every living thing on the face of the planet, it just isnt going to understand you. No matter how much you think it should understand you IT ISNT GOING TO. PERIOD. It is up to you to state exactly what you want with exactly the right syntax EVERY SINGLE SOLITARY TIME WITHOUT EXCEPTION. Comments # comments follow a pound sign Help Variables : x = 9+1j name = "john" age = 36 age_string = str(age) length_of_age_string = len(age_string) age_stringstart:end # Start character is included. End character is not included. The first character is character #0. See Slicing. todays_date = "1 jan 2018" it_is_january = "jan" in todays_date # it_is_january = true it_is_february = "feb" in todays_date # it_is_february = false OrderedList = item", 2, "third item" # OrderedList0 = "first item" Back to top Input and output print(name, "is", age, "years old") # default separater is a single space. default end is new line print("this is printed on a new line") print("But we can change the def", "ault separator and default end", sep="", end="") print("This is not printed on a new line") print("a\tbx\tc\n12345678901234567890") # \t is tab and \n is new line. your_input = input("please enter your input: ") produces: john is 36 years old this is printed on a new line But we can change the default separator and default endThis is not printed on a new line a bx c 12345678901234567890 please enter your input: Back to top Loops : for num in range(1000, 2000, 100): # prints 1000 to 1900 in steps of 100 ::print (num) num = 0 while num < 10: # dont forget the colon ::print (num) ::num = num + 1 Back to top Conditional statements : young = age < 10 old = age > 65 middle_age = (45 < age < 65) if young: # dont forget the colon at the end ::print (name, "is young") elif old: ::print (name, "is old") elif middle_age: ::print (name, "is middle age") else: ::print (name, "is neither young nor old nor middle age") Back to top Functions : def convert_to_celcius(fahrenheit): ::"""Converts fahrenheit to celcius""" # documentation that is printed out when we use help("convert_to_celcius") ::return (fahrenheit-32)*5/9 print (convert_to_celcius(212)) Back to top Importing modules After importing a module you can use help("module name") to get info. ::Template:Help("time") ::Template:Help("math") import time time.sleep(15) # delay for 15 seconds import math x = math.sqrt(9) # x = sqrt(9) wont work. You must use math.sqrt import math as mt x = mt.sqrt(9) from math import sqrt x = sqrt(9) # no need for math.sqrt since sqrt has been imported into the current namespace There is nothing fancy about a module. Its just a program containing program definitions. The program is executed when it is imported unless it was previously imported. You can easily create your own modules. dir(module_name) # returns a list of all the functions in the module. Easier to read if converted to an array. Back to top Classes Tutorial Calling methods is very similar to calling functions in a module. Instead of module.function(arguments) you use class.method(arguments). str.capitalize("string") # returns the string with first letter capitalized In a perfect world modules and classes would be the same thing because every module would correspond to exactly one class of object. But we dont live in that world. type(any_object) # returns the class of the object When we call a method, the object itself is passed as the first parameter (called "self"). class Person: :def __init__(self, name, birthday): ::self.name = name ::self.birthday = birthday :def age(self): ::today = datetime.date.today() ::age = today.year - self.birthdate.year ::return age person1 = Person("Bill", datetime.date(1981, 12, 27) ) Back to top Text files with open("TextFile.txt", "r") as file: ::contents = file.read() with open("TextFile.txt", "r") as file: ::List_of_lines = file.readlines() with open("TextFile.txt", "w") as output_file: ::output_file.write(contents) Back to top Database Creating: import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor() cur.execute('CREATE TABLE test(name TEXT, age INTEGER)') cur.execute('INSERT INTO test VALUES("John", 33)') cur.execute('INSERT INTO test VALUES("Alice", 21)') x=18 cur.execute('INSERT INTO test VALUES(?, ?)', x) con.commit() # changes are not committed until this command cur.execute('SELECT * FROM test WHERE age > 5 ORDER BY name') whole_table = cur.fetchall() print (whole_table) con.close() Updating" import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor() cur.execute('DELETE FROM test WHERE name = "John"') cur.execute('UPDATE test SET age = 99 WHERE name = "Alice"') # if there is more than one Mary then they both get updated cur.execute('SELECT * FROM test WHERE age > 5 ORDER BY name') whole_table = cur.fetchall() print (whole_table) con.close() Back to top Pandas Tutorial and Cheatsheet You can easily create a dataframe from an array but the array must be 2 dimensional even if there is only one row. (2 brackets not 1) import numpy as np import pandas as pd y = np.array( [ 1,2,3,4 ] ) df = pd.DataFrame( y, index=1,2, columns="a","b" ) print (df) Produces: a b 1 1 2 2 3 4 We can then drop a row: df=df.drop(1) print (df, "\n") Produces: a b 2 3 4 We can create a second dataframe and append it to the first: z = np.array([ 5,6 ]) # Even though the data is one dimensional we must use the two dimensional format (2 brackets) df2 = pd.DataFrame( z, index=3, columns="b","a") # if z was one dimensional we could have used z df=df.append(df2) print (df, "\n") Produces: a b 2 3 4 3 6 5 Back to top Internet The following code prints each line of the webpage minus most of the html markup. tag = False quote = False import urllib.request with urllib.request.urlopen("https://en.wikipedia.org/wiki/Hiroshi_Sakagami") as webpage: ::for line in webpage: :::out = "" :::line = line.strip() :::line = line.decode('utf-8') :::if line "": ::::print (line) :::elif line0:7 "": ::::line = "" :::else: ::::for c in line: :::::if c '<' and not quote: ::::::tag = True :::::elif c '>' and not quote: ::::::tag = False :::::elif (c '"' or c "'") and tag: ::::::quote = not quote :::::elif not tag: ::::::out = out + c ::::if out != "": :::::print(out) x=input("press enter when done") Back to top Numpy Arrays import numpy as np x = np.array([1,2,3,4,5,6]) print (x) produces: [2 3 5 6] Math operations + and * operate elementwise and create a new matrix. To modify an existing array use += and *= For matrix multiplication use @ Back to top Scipy tutorial To import two subpackages you would use: from scipy import subpackage1, subpackage2 Back to top Sympy Galgebra tutorial Back to top Matplotlib Tutorial import matplotlib as mpl import matplotlib.pyplot as plt Back to top External links * https://www.packtpub.com/tech/Python Copyright